package com.xms.security.service.cascade;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xms.dependency.XmsDependencyException;
import com.xms.security.entity.RoleObjectAccess;
import com.xms.security.entity.Roles;
import com.xms.security.event.RoleDeletedEvent;
import com.xms.security.service.dataauth.IRoleObjectAccessService;
import com.xms.utils.CollectionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色删除后，级联删除授权信息
 * </p>
 *
 * @author migo
 * @since 2021/10/26
 */
@Service
public class RoleObjectAccessCascadeDeleter {
    private IRoleObjectAccessService _roleObjectAccessService;

    @Autowired
    public void RoleObjectAccessCascadeDelete(IRoleObjectAccessService roleObjectAccessService) {
        _roleObjectAccessService = roleObjectAccessService;
    }

    public boolean cascadeDelete(Roles... parent) {
        if (CollectionUtil.isEmpty(parent)) {
            List<UUID> ids = Arrays.stream(parent).map(x -> x.getRoleid()).collect(Collectors.toList());
            return _roleObjectAccessService.remove(new LambdaQueryWrapper<RoleObjectAccess>()
                    .eq(RoleObjectAccess::getRoleid, ids));
        }
        return false;
    }

    @Async
    @EventListener()
    public void onApplicationEvent(RoleDeletedEvent event) throws XmsDependencyException, SQLException {
        this.cascadeDelete(event.source);
    }
}
